<template>
  <div
    class="-translate-x-14 transition-all duration-1000"
    :class="{ 'translate-x-4 -rotate-45': hideRobot }"
    @mouseover="(hideRobot = false), (showPopover = true)"
  >
  world
    <el-popover
      placement="top"
      popper-class="robot-popper !bg-transparent"
      :width="popoverWidth"
      :visible="showPopover"
      :transition="'el-zoom-in-bottom'"
      ref="popoverRef"
    >
      <template #reference>
        <div>
          <div class="robot-container float-robot" @click="openPanel" id="robot"></div>
        </div>
      </template>
      <div class="p-4 rounded-md">
        <!-- 文本消息 -->
        <div v-if="robotMessage.type === 'text'" class="text-base font-semibold">
          {{ robotMessage.content }}
        </div>

        <!-- 新闻列表消息 -->
        <div
          v-else-if="robotMessage.type === 'news'"
          @mouseover="showScrollBar = true"
          @mouseout="showScrollBar = false"
        >
          <span class="text-base font-semibold flex justify-between items-center">
            <span>{{ (robotMessage.content as NewsMessage).title }}</span>
            <CloseQuote @click="miniRobot" class="cursor-pointer" />
          </span>
          <p class="text-text-02 black:text-text-02-dark text-xs font-normal mt-2">
            #{{ appInfoStore.appInfo?.stock.stock_name }}#{{
              (robotMessage.content as NewsMessage).desc
            }}
          </p>
          <div
            class="max-h-[380px] overflow-y-auto overflow-x-hidden mt-2"
            :class="{ 'no-scrollbar': !showScrollBar }"
          >
            <TransitionGroup name="list" tag="div">
              <div
                v-for="(item, index) in (robotMessage.content as NewsMessage).data"
                class="border-gradient mt-[6px] px-3 py-[6px] text-sm"
                :class="{ 'cursor-pointer': item.contentUrl }"
                :key="item.contentId"
                @click="openUrl(item)"
                v-track:click="{ id: 'thspc_f10_copilot_copliotbot_news', logmap: () => {} }"
              >
                {{ getIcon(index) }}
                {{ item.eventContent }}
              </div>
            </TransitionGroup>
          </div>
        </div>

        <!-- 推荐问句消息 -->
        <div v-else-if="robotMessage.type === 'question'">
          <span
            class="text-xs text-text-02 black:text-text-02-dark flex justify-between items-center"
          >
            <span>猜你想问</span>
            <CloseQuote @click="miniRobot" class="cursor-pointer" />
          </span>
          <div class="flex flex-wrap mt-[6px] justify-start gap-2 items-center">
            <span
              class="px-2 py-[6px] rounded w-full border-border-02 black:border-border-02-dark border max-w-full bg-background-01 black:bg-background-01-dark text-sm text-text-04 black:text-text-04 flex justify-start items-center gap-2 cursor-pointer hover:border-border-04 black:hover:border-border-04-dark hover:bg-aif10enterbg"
              v-for="(item, index) in (robotMessage.content as QuestionMessage).data"
              :key="index"
              @click="sendRobotMessage('question', item)"
              v-track:click="{
                id: 'thspc_f10_copilot_copliotbot_recomed',
                logmap: () => ({ content: item })
              }"
            >
              <el-icon><QuestionEnter /></el-icon>
              <div class="truncate">{{ item }}</div>
            </span>
          </div>
        </div>

        <!-- 内容选中消息 -->
        <div v-else-if="robotMessage.type === 'contentSelect'">
          <span class="text-xs flex justify-between items-center">
            <span class="flex items-center justify-start gap-[6px]">
              <el-icon class="!text-text-01 black:!text-text-01-dark">
                <SelectSection
                  v-if="(robotMessage.content as ContentSelectMessage).selectType === 'SECTION'"
                />
                <SelectContent v-else />
              </el-icon>
              {{ SELECTTYPE[(robotMessage.content as ContentSelectMessage).selectType] }}
            </span>
            <CloseQuote @click="miniRobot" class="cursor-pointer" />
          </span>
          <p class="text-text-02 black:text-text-02-dark text-xs font-normal mt-2 truncate">
            {{ (robotMessage.content as ContentSelectMessage).selectContent }}
          </p>
          <!-- 命令行工具 -->
          <div class="tools flex justify-end items-center gap-2 mt-2">
            <span
              class="text-xs h-6 px-2 bg-background-03 black:bg-background-03-dark rounded text-text-04 black:text-text-04-dark flex justify-center items-center cursor-pointer hover:bg-aif10enterbg"
              v-for="item in (robotMessage.content as ContentSelectMessage).chatCommands"
              :key="item.id"
              @click="sendRobotMessage('command', item)"
              v-track:click="{
                id: 'thspc_f10_copilot_copliotbot_command',
                logmap: () => ({ type: item.id, content: item.name })
              }"
            >
              {{ item.name }}
            </span>
          </div>
          <el-input
            v-model="question"
            class="w-full !caret-text-04 black:!caret-text-04-dark bg-background-01 black:bg-background-01-dark mt-2"
            :placeholder="placeholder"
            @keyup.enter.prevent="sendRobotMessage('question', question)"
          >
            <template #suffix>
              <el-icon
                class="cursor-pointer"
                :class="{ 'opacity-60': !question, 'cursor-not-allowed': !question }"
                @click="sendRobotMessage('question', question)"
                ><SendMessage
              /></el-icon>
            </template>
          </el-input>
        </div>
      </div>
    </el-popover>
  </div>
</template>

<script setup lang="ts">
import { CloseQuote } from '@/components/icons'
import { computed, nextTick, onMounted, ref, watch, type Ref } from 'vue'
import { getEventBus } from '@/common/services/chat-event-bus'
import { SELECTTYPE } from '@/common/config/const'
import type {
  ContentSelectMessage,
  NewsMessage,
  QuestionMessage,
  RobotMessage
} from '@/common/models/robot-message'
import { usePanelStore } from '@/stores/panel'
import type { RefrenceResource } from '@/common/models/chat-message'
import type { Section } from '@/common/models/recommend-result'
import { getRecommendQuestion, getRobotMessage } from '../services/chat-api'
import { useAppInfoStore } from '@/stores/app'
import type { EventItem } from '@/common/models/event-summary'

const props = defineProps<{
  chatAskBox: any
  showChatPanel: boolean
}>()

const showPanel = computed(() => props.showChatPanel)

const popoverRef: Ref<any> = ref(null)

const showScrollBar = ref(false)

watch(showPanel, (newVal) => {
  setTimeout(() => {
    showPopover.value = !newVal
  }, 500)
})

const emits = defineEmits(['showPanel'])

const { robotMessageEventBus, robotQuestionEventBus } = getEventBus()

const showPopover = ref(false)

const hideRobot = ref(false)

const question = ref('')

const placeholder = ref('询问有关的问题...')

const miniRobot = () => {
  showPopover.value = false
  hideRobot.value = true
}

const panelStore = usePanelStore()
const appInfoStore = useAppInfoStore()

const popoverWidth = ref('160px')

const welcomeText = () => {
  const now = new Date()
  const hour = now.getHours()

  if (hour >= 5 && hour < 8) {
    return '👋 Hi，早上好!'
  } else if (hour >= 8 && hour < 11) {
    return '👋 Hi，上午好!'
  } else if (hour >= 11 && hour < 13) {
    return '👋 Hi，中午好!'
  } else if (hour >= 13 && hour < 17) {
    return '👋 Hi，下午好!'
  } else {
    return '👋 Hi，晚上好！'
  }
}

const getIcon = (index: number) => {
  const iconsArr = ['🔍', '📄', '📣', '💬', '📢', '💡', '👀']
  return iconsArr[index % iconsArr.length]
}

const robotMessage: Ref<RobotMessage> = ref({
  width: '160px',
  type: 'text',
  flush: true,
  content: welcomeText()
})

const newsMock: Ref<RobotMessage> = ref({
  type: 'news',
  width: '320px',
  flush: true,
  content: {
    title: welcomeText(),
    desc: `最近发生这些事件，可以关注一下～`,
    data: []
  }
})

onMounted(() => {
  setTimeout(() => {
    showPopover.value = true
    setTimeout(async () => {
      const res = await getRobotMessage()
      console.log(res)

      const data: EventItem[] = []

      res.eventData.forEach((item) => {
        item.viewEvent.forEach((view) => {
          data.push(view)
        })
      })
      if (data.length === 0) {
        ;(newsMock.value.content as NewsMessage).desc =
          '最近暂未发生重要事件，可以关注个股未来走势~'
      }
      changeRobotMessage(newsMock.value)
      data.slice(0, 6).forEach((item, index) => {
        setTimeout(
          () => {
            ;(newsMock.value.content as NewsMessage).data.push(item)
          },
          500 * (index + 1)
        )
      })
    }, 3000)
  }, 500)
})

const changeRobotMessage = (msg: RobotMessage | null) => {
  const message = msg || newsMock.value
  if (hideRobot.value || showPanel.value || !msg?.flush) {
    popoverWidth.value = message.width
    robotMessage.value = message
    return
  }
  showPopover.value = false
  setTimeout(() => {
    popoverWidth.value = message.width
    showPopover.value = true
    robotMessage.value = message
  }, 100)
}

// 监听：机器人消息事件
robotMessageEventBus.on(changeRobotMessage)

// 监听：机器人问句事件
robotQuestionEventBus.on(async ({ section }) => {
  if (panelStore.selectSection || showPanel.value) return
  const params = formatRefParam(section)
  const res = await getRecommendQuestion(params)
  const questions = res.questions.sort((pre, next) => pre.length - next.length).slice(0, 2)
  changeRobotMessage({
    type: 'question',
    width: '320px',
    flush: true,
    content: { data: questions }
  })
})

// 设置引用内容请求参数
function formatRefParam(section: Section): RefrenceResource {
  const panel = panelStore.currentPanel
  return {
    type: 'SECTION',
    select_title: section.title,
    select_content: section.title,
    data: null,
    section_name: section?.title || null,
    sid: section?.id || null,
    pid: panel?.id || null,
    panel_name: panel?.title || null
  }
}

async function openPanel() {
  showPopover.value = false
  await nextTick()
  emits('showPanel')
}

async function sendRobotMessage(type: string, data: any) {
  question.value = ''
  if (type === 'question') {
    showPopover.value = false
    await nextTick()
    emits('showPanel')
    props.chatAskBox.sendMessage(data)
    setTimeout(() => {
      robotMessage.value = newsMock.value
    }, 500)
  }
  if (type === 'command') {
    props.chatAskBox.commondClick(data)
    if (data.id === 'card_edit') {
      placeholder.value = `将“${panelStore.selectSection?.value}”修改为：`
      return
    }
    if (data.id === 'visual_insight') {
      placeholder.value = `输入洞察要素，如：最大值、平均值等`
      return
    }
    if (['card_delete'].includes(data.id)) {
      changeRobotMessage(newsMock.value)
      return
    }
    if (['card_change'].includes(data.id)) {
      return
    }
    showPopover.value = false
    await nextTick()
    emits('showPanel')
    setTimeout(() => {
      robotMessage.value = newsMock.value
    }, 500)
  }
}

function openUrl(item: EventItem) {
  if (!item.contentUrl) return
  window.open(item.contentUrl)
}
</script>
